<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />





  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "0b6e024b"
    });
  daovoice('update');
  </script>














  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Android,Android编程权威指南(第2版)," />










<meta name="keywords" content="Android,Android编程权威指南(第2版)">
<meta property="og:type" content="article">
<meta property="og:title" content="Android编程权威指南（第2版）学习笔记 --第29章 定制视图与触摸时间 挑战练习">
<meta property="og:url" content="http://yoursite.com/2018/08/31/android/Android编程权威指南/android-note-12/index.html">
<meta property="og:site_name" content="万般皆下品 唯有读书高">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/9140378-86a4d99c8f8c8470.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-09-02T07:46:17.755Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android编程权威指南（第2版）学习笔记 --第29章 定制视图与触摸时间 挑战练习">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/9140378-86a4d99c8f8c8470.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/08/31/android/Android编程权威指南/android-note-12/"/>





  <title>Android编程权威指南（第2版）学习笔记 --第29章 定制视图与触摸时间 挑战练习 | 万般皆下品 唯有读书高</title>
  








</head>


   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas>
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script>
   <script type="text/javascript" src="/js/src/fireworks.js"></script>


<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">万般皆下品 唯有读书高</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">小生的学习笔记</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/08/31/android/Android编程权威指南/android-note-12/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="HyYyr Wang">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/icon.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="万般皆下品 唯有读书高">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Android编程权威指南（第2版）学习笔记 --第29章 定制视图与触摸时间 挑战练习</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-31T15:49:03+08:00">
                2018-08-31
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index">
                    <span itemprop="name">Android</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,456
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  11
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://upload-images.jianshu.io/upload_images/9140378-86a4d99c8f8c8470.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="u=1269396152,216456559&amp;fm=26&amp;gp=0.jpg"></p>
<hr>
<a id="more"></a>
<h2 id="创建定制视图"><a href="#创建定制视图" class="headerlink" title="创建定制视图"></a>创建定制视图</h2><h3 id="Android-视图分类"><a href="#Android-视图分类" class="headerlink" title="Android 视图分类"></a>Android 视图分类</h3><ul>
<li>简单视图。简单视图内部也可以很复杂;之所以归为简单类别，是因为简单视图不包括子视图。而且，简单视图几乎总是会执行定制绘制</li>
<li>聚合视图。聚合视图由其他视图对象组成。聚合视图通常管理着子视图，但不负责执行定制绘制。图形绘制任务都委托给了各个子视图</li>
</ul>
<h3 id="创建定制视图三步骤"><a href="#创建定制视图三步骤" class="headerlink" title="创建定制视图三步骤"></a>创建定制视图三步骤</h3><ul>
<li>聚合视图。聚合视图由其他视图对象组成。聚合视图通常管理着子视图，但不负责执行定制绘制。图形绘制任务都委托给了各个子视图</li>
<li>继承选定的超类，并至少覆盖一个超类构造方法</li>
<li>覆盖其他关键方法，以定制视图行为</li>
</ul>
<h3 id="创建BoxDrawingView"><a href="#创建BoxDrawingView" class="headerlink" title="创建BoxDrawingView"></a>创建BoxDrawingView</h3><h4 id="BoxDrawingView-是一个简单的视图，同时也是View的直接子类"><a href="#BoxDrawingView-是一个简单的视图，同时也是View的直接子类" class="headerlink" title="BoxDrawingView 是一个简单的视图，同时也是View的直接子类"></a>BoxDrawingView 是一个简单的视图，同时也是View的直接子类</h4><p>以View为超类，创建一个初始的视图类<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BoxDrawingView</span> <span class="keyword">extends</span> <span class="title">View</span></span>&#123;</span><br><span class="line">   <span class="comment">//  Used when creating the view in code</span></span><br><span class="line">    <span class="comment">//  在代码中创建视图时使用</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BoxDrawingView</span><span class="params">(Context context)</span></span>&#123;</span><br><span class="line">        <span class="keyword">this</span>(context,<span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//  Used when inflating the view from XML</span></span><br><span class="line">    <span class="comment">// 从XML扩展视图时使用</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BoxDrawingView</span><span class="params">(Context context, AttributeSet attrs)</span></span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(context,attrs);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="在布局当中添加该View"><a href="#在布局当中添加该View" class="headerlink" title="在布局当中添加该View"></a>在布局当中添加该View</h4><ul>
<li>注意在引用时我们必须使用自定义 View 的全路径类名，这样布局 inflater 才能够找到它</li>
<li>布局 inflater 解析布局 XML 文件，并按视图定义创建 View 实例。如果元素名不是全路径类名，布局 inflater 会转而在 android.view 和 android.widget 包中寻找目标。如果目标视图类放置在其他包中，布局 inflater 将无法找到目标并最终导致应用崩溃<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version="1.0" encoding="utf-8"?&gt;</span><br><span class="line"><span class="tag">&lt;<span class="name">com.example.lab.android.nuc.draganddraw.view.BoxDrawingView</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:android</span>=<span class="string">"http://schemas.android.com/apk/res/android"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:tools</span>=<span class="string">"http://schemas.android.com/tools"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:layout_width</span>=<span class="string">"match_parent"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">android:layout_height</span>=<span class="string">"match_parent"</span>/&gt;</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="处理触摸事件"><a href="#处理触摸事件" class="headerlink" title="处理触摸事件"></a>处理触摸事件</h2><h3 id="触摸事件简介"><a href="#触摸事件简介" class="headerlink" title="触摸事件简介"></a>触摸事件简介</h3><ul>
<li><p>监听触摸事件的一种方式是使用一下View的方法，设置一个触摸事件监听器:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setOnTouchListener</span><span class="params">(View.OnTouchListener l)</span></span></span><br></pre></td></tr></table></figure>
</li>
<li><p>该方法的工作方式与setOnClickListener(View.OnClickListener)相同。实现View.OnTouchListener接口，供触摸事件发生时调用</p>
</li>
<li><p>由于我们定制的视图是View的子类，因此可直接覆盖以下的方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onTouchEvent</span><span class="params">(MotionEvent event)</span></span></span><br></pre></td></tr></table></figure>
</li>
<li><p>该方法接受一个MotionEvent类实例，MotionEvent类可用来描述包括位置和动作的触摸事件。动作用于描述事件所处的阶段</p>
</li>
</ul>
<table>
<thead>
<tr>
<th style="text-align:center">动作常量</th>
<th style="text-align:center">动作描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">———————————————</td>
<td style="text-align:center">———————————————–</td>
</tr>
<tr>
<td style="text-align:center">ACTION_DOWN</td>
<td style="text-align:center">手指触摸到屏幕</td>
</tr>
<tr>
<td style="text-align:center">ACTION_MOVE</td>
<td style="text-align:center">手指在屏幕上移动</td>
</tr>
<tr>
<td style="text-align:center">ACTION_UP</td>
<td style="text-align:center">手指离开屏幕</td>
</tr>
<tr>
<td style="text-align:center">ACTION_CANCEL</td>
<td style="text-align:center">父视图拦截了触摸事件</td>
</tr>
</tbody>
</table>
<h3 id="实现BoxDrawingView视图类"><a href="#实现BoxDrawingView视图类" class="headerlink" title="实现BoxDrawingView视图类"></a>实现BoxDrawingView视图类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BoxDrawingView</span> <span class="keyword">extends</span> <span class="title">View</span></span>&#123;</span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String TAG = <span class="string">"BoxDrawingView"</span>;</span><br><span class="line"></span><br><span class="line">  ......</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onTouchEvent</span><span class="params">(MotionEvent event)</span> </span>&#123;</span><br><span class="line">        PointF current = <span class="keyword">new</span> PointF( event.getX(),event.getY());</span><br><span class="line">        String action = <span class="string">""</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">switch</span> (event.getActionMasked())&#123;</span><br><span class="line">            <span class="keyword">case</span> MotionEvent.ACTION_DOWN:</span><br><span class="line">                action = <span class="string">"ACTION_DOWN"</span>;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> MotionEvent.ACTION_MOVE:</span><br><span class="line">                action = <span class="string">"ACTION_MOVE"</span>;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> MotionEvent.ACTION_POINTER_DOWN:</span><br><span class="line">                action = <span class="string">"POINTER_DOWN"</span>;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> MotionEvent.ACTION_UP:</span><br><span class="line">                action = <span class="string">"ACTION_UP"</span>;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> MotionEvent.ACTION_CANCEL:</span><br><span class="line">                action = <span class="string">"ACTION_CANCEL"</span>;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        Log.e( TAG,action + <span class="string">" at x = "</span> + current.x +</span><br><span class="line">                <span class="string">",y = "</span> + current.y);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>现在X和Y坐标已经封装到PointF对象中，现在需要同时传递这两个坐标值，而Android提供的PointF容器刚好满足了这一需求</li>
</ul>
<h2 id="跟踪运动事件"><a href="#跟踪运动事件" class="headerlink" title="跟踪运动事件"></a>跟踪运动事件</h2><h3 id="首先，要知道定义矩形的两个坐标点，需要定义一个类用于储存这两个坐标值"><a href="#首先，要知道定义矩形的两个坐标点，需要定义一个类用于储存这两个坐标值" class="headerlink" title="首先，要知道定义矩形的两个坐标点，需要定义一个类用于储存这两个坐标值"></a>首先，要知道定义矩形的两个坐标点，需要定义一个类用于储存这两个坐标值</h3><p>新建一个一个 <a href="https://github.com/wanghao15536870732/Android-programming-authority-guide/blob/master/DragAndDraw/app/src/main/java/com/example/lab/android/nuc/draganddraw/base/Box.java" target="_blank" rel="noopener">Box.java</a> 类<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Box</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> PointF mOrigin;</span><br><span class="line">    <span class="keyword">private</span> PointF mCurrent;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Box</span><span class="params">(PointF origin)</span></span>&#123;</span><br><span class="line">        mOrigin = origin;</span><br><span class="line">        mCurrent = origin;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setOrigin</span><span class="params">(PointF origin)</span> </span>&#123;</span><br><span class="line">        mOrigin = origin;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> PointF <span class="title">getCurrent</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> mCurrent;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> PointF <span class="title">getOrigin</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> mOrigin;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setCurrent</span><span class="params">(PointF current)</span> </span>&#123;</span><br><span class="line">        mCurrent = current;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="添加拖拽生命周期方法-BoxDrawingView-java"><a href="#添加拖拽生命周期方法-BoxDrawingView-java" class="headerlink" title="添加拖拽生命周期方法  BoxDrawingView.java"></a>添加拖拽生命周期方法  <a href="https://github.com/wanghao15536870732/Android-programming-authority-guide/blob/master/DragAndDraw/app/src/main/java/com/example/lab/android/nuc/draganddraw/view/BoxDrawingView.java" target="_blank" rel="noopener">BoxDrawingView.java</a></h3><ul>
<li>当用户手指在屏幕上滑动时，mCurrentBox。mCurrent会得到更新，在取消触摸事件或用户用手指开屏幕时，我们应清空mCurrentBox以结束屏幕绘制</li>
<li>ACTION_MOVE事件发生时调用的invalidate()方法，该方法会强制BoxDrawingView重新绘制自己<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BoxDrawingView</span> <span class="keyword">extends</span> <span class="title">View</span></span>&#123;</span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String TAG = <span class="string">"BoxDrawingView"</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">private</span> Box mCurrentBox;</span><br><span class="line">  <span class="keyword">private</span> List&lt;Box&gt; mBoxen = <span class="keyword">new</span> ArrayList&lt;&gt;( );</span><br><span class="line">  ......</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onTouchEvent</span><span class="params">(MotionEvent event)</span> </span>&#123;</span><br><span class="line">        PointF current = <span class="keyword">new</span> PointF( event.getX(),event.getY());</span><br><span class="line">        String action = <span class="string">""</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">switch</span> (event.getActionMasked())&#123;</span><br><span class="line">            <span class="keyword">case</span> MotionEvent.ACTION_DOWN:</span><br><span class="line">                action = <span class="string">"ACTION_DOWN"</span>;</span><br><span class="line">                mCurrentBox = <span class="keyword">new</span> Box( current);</span><br><span class="line">                mBoxen.add( mCurrentBox );</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> MotionEvent.ACTION_MOVE:</span><br><span class="line">                action = <span class="string">"ACTION_MOVE"</span>;</span><br><span class="line">                <span class="keyword">if</span> (mCurrentBox != <span class="keyword">null</span>) &#123;</span><br><span class="line">                  <span class="comment">//如果只有一只手指按下，而且还未曾旋转过的话，就进行大小的缩放</span></span><br><span class="line">                  mCurrentBox.setCurrent(current);</span><br><span class="line">                  invalidate();</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> MotionEvent.ACTION_UP:</span><br><span class="line">                action = <span class="string">"ACTION_UP"</span>;</span><br><span class="line">                mCurrentBox = <span class="keyword">null</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> MotionEvent.ACTION_CANCEL:</span><br><span class="line">                action = <span class="string">"ACTION_CANCEL"</span>;</span><br><span class="line">                mCurrentBox = <span class="keyword">null</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        Log.e( TAG,action + <span class="string">" at x = "</span> + current.x +</span><br><span class="line">                <span class="string">",y = "</span> + current.y);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="onDraw-…-方法内的绘制图形"><a href="#onDraw-…-方法内的绘制图形" class="headerlink" title="onDraw(…)方法内的绘制图形"></a>onDraw(…)方法内的绘制图形</h2><h3 id="onDeaw绘制简介"><a href="#onDeaw绘制简介" class="headerlink" title="onDeaw绘制简介"></a>onDeaw绘制简介</h3><ul>
<li>应用启动时，所有视图都处于无效状态。</li>
<li>也就是说，视图还没有绘制到屏幕上。为解决这个问题，Android 调用了顶级 View 视图的 draw()方法。这会引起自上而下的链式调用反应。</li>
<li>首先，视图完成自我绘制，然后是子视图的自我绘制，再然后是子视图的子视图的自我绘制，如此调用下去直至继承结构的末端。</li>
<li><p>当继承结构中的所有视图都完成自我绘制后，最顶级 View 视图也就生效了。<br>为加入这种绘制，可覆盖以下 View 方法:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onDraw</span><span class="params">(Canvas canvas)</span></span></span><br></pre></td></tr></table></figure>
</li>
<li><p>Canvas 和 Paint 是 Android 系统的两大绘制类:</p>
<ul>
<li>Canvas 类拥有我们需要的所有绘制操作。其方法可决定绘在哪里以及绘什么，比如线条、圆形、字词、矩形等</li>
<li>Paint 类决定如何绘制。其方法可指定绘制图形的特征，例如是否填充图形、使用什么字<br>体绘制、线条是什么颜色等<h3 id="创建Point"><a href="#创建Point" class="headerlink" title="创建Point"></a>创建Point</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BoxDrawingView</span> <span class="keyword">extends</span> <span class="title">View</span></span>&#123;</span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String TAG = <span class="string">"BoxDrawingView"</span>;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">private</span> Box mCurrentBox;</span><br><span class="line">   <span class="keyword">private</span> List&lt;Box&gt; mBoxen = <span class="keyword">new</span> ArrayList&lt;&gt;( );</span><br><span class="line"></span><br><span class="line">   <span class="keyword">private</span> Paint mBoxPaint;</span><br><span class="line">   <span class="keyword">private</span> Paint mBackgroundPaint;</span><br><span class="line"></span><br><span class="line">  ...</span><br><span class="line"></span><br><span class="line">  <span class="comment">//  Used when inflating the view from XML</span></span><br><span class="line">    <span class="comment">// 从XML扩展视图时使用</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BoxDrawingView</span><span class="params">(Context context, AttributeSet attrs)</span></span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(context,attrs);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//Paint the Box a nice semitransparent red (ARGB)</span></span><br><span class="line">        <span class="comment">// 漆成漂亮的半透明红色(ARGB)</span></span><br><span class="line">        mBoxPaint = <span class="keyword">new</span> Paint( );</span><br><span class="line">        mBoxPaint.setColor( <span class="number">0x22ff0000</span> );</span><br><span class="line"></span><br><span class="line">        <span class="comment">//Paint the background off-white</span></span><br><span class="line">        <span class="comment">//  白色背景</span></span><br><span class="line">        mBackgroundPaint = <span class="keyword">new</span> Paint( );</span><br><span class="line">        mBackgroundPaint.setColor( <span class="number">0xfff8efe0</span> );</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
<li><p>有了Point对象的支持，现在可以在屏幕上绘制矩形框了</p>
<h3 id="4-3-覆盖onDraw-方法"><a href="#4-3-覆盖onDraw-方法" class="headerlink" title="4.3 覆盖onDraw()方法"></a>4.3 覆盖onDraw()方法</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BoxDrawingView</span> <span class="keyword">extends</span> <span class="title">View</span></span>&#123;</span><br><span class="line"></span><br><span class="line">  ......</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onDraw</span><span class="params">(Canvas canvas)</span> </span>&#123;</span><br><span class="line">        canvas.drawPaint(mBackgroundPaint);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (Box box : mBoxen)&#123;</span><br><span class="line">            <span class="keyword">float</span> left = Math.min( box.getOrigin().x,box.getCurrent().x );</span><br><span class="line">            <span class="keyword">float</span> right = Math.max( box.getOrigin().x,box.getCurrent().x);</span><br><span class="line">            <span class="keyword">float</span> top = Math.min( box.getOrigin().y,box.getCurrent().y );</span><br><span class="line">            <span class="keyword">float</span> bottom = Math.max( box.getOrigin().y,box.getCurrent().y);</span><br><span class="line">            canvas.drawRect( left,top,right,bottom,mBoxPaint);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="5-挑战练习"><a href="#5-挑战练习" class="headerlink" title="5. 挑战练习"></a>5. 挑战练习</h2><h3 id="5-1-设备旋转问题"><a href="#5-1-设备旋转问题" class="headerlink" title="5.1 设备旋转问题"></a>5.1 设备旋转问题</h3><ul>
<li>修改 <a href="https://github.com/wanghao15536870732/Android-programming-authority-guide/blob/master/DragAndDraw/app/src/main/java/com/example/lab/android/nuc/draganddraw/view/BoxDrawingView.java" target="_blank" rel="noopener">BoxDrawingView.java</a> 类，添加onSaveInstanceState()以及onRestoreInstanceState()方法</li>
<li>使用 Bundle 传递需要存储的参数<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BoxDrawingView</span> <span class="keyword">extends</span> <span class="title">View</span></span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//要给整个视图加上 ID，onSaveInstanceState()以及</span></span><br><span class="line">  <span class="comment">//onRestoreInstanceState()方法才会被调用</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String</span><br><span class="line">            TAG = <span class="string">"BoxDrawingView"</span>,</span><br><span class="line">            KEY_SUPER_DATA = <span class="string">"key_super_data"</span>,</span><br><span class="line">            KEY_BOXEN = <span class="string">"key_boxen"</span>;</span><br><span class="line"></span><br><span class="line">    ......</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Parcelable <span class="title">onSaveInstanceState</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Bundle bundle = <span class="keyword">new</span> Bundle( );</span><br><span class="line">        <span class="comment">// 存储父类需要存储的内容</span></span><br><span class="line">        Parcelable superData = <span class="keyword">super</span>.onSaveInstanceState();</span><br><span class="line">        bundle.putParcelable(KEY_SUPER_DATA, superData);</span><br><span class="line">        <span class="comment">// 存储所有的矩形</span></span><br><span class="line">        bundle.putSerializable(KEY_BOXEN, (ArrayList) mBoxen);</span><br><span class="line">        invalidate();</span><br><span class="line">        <span class="keyword">return</span> bundle;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onRestoreInstanceState</span><span class="params">(Parcelable state)</span> </span>&#123;</span><br><span class="line">        Bundle bundle = (Bundle) state;</span><br><span class="line">        Parcelable superData = bundle.getParcelable( KEY_SUPER_DATA );</span><br><span class="line">        mBoxen = (ArrayList&lt;Box&gt;) bundle.getSerializable( KEY_BOXEN );</span><br><span class="line">        <span class="keyword">super</span>.onRestoreInstanceState( superData );</span><br><span class="line">        invalidate();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    .....</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="5-2-旋转矩形框"><a href="#5-2-旋转矩形框" class="headerlink" title="5.2 旋转矩形框"></a>5.2 旋转矩形框</h3><ul>
<li>需要使用 MotionEvent.getActionMasked() 方法来获取事件 ID，处理多点触控</li>
<li>ACTION_POINTER_DOWN  指的是屏幕上已经有手指了，并且另一根手指按下的情况，也就是说现在已经指导两个手指都按下了</li>
<li>图形的旋转一般是在绘制的时候旋转画布（canvas），需要的参数有旋转的角度（用度表示）以及旋转中心坐标</li>
<li>在 Box 类中加入最开始的角度 mOriginAngle，已旋转后的角度 mRotatedAngle 两个成员变量，以及一个获取中心点坐标的方法</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"> <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Box</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line">    <span class="comment">//此次按下的角度</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">float</span> mOriginAngle;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">float</span> mCurrentAngle;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Box</span><span class="params">(PointF origin)</span></span>&#123;</span><br><span class="line">        mOrigin = origin;</span><br><span class="line">        mCurrent = origin;</span><br><span class="line">        mOriginAngle = <span class="number">0</span>;</span><br><span class="line">        mCurrentAngle = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    getter()、setter()方法 ...</span><br><span class="line"></span><br><span class="line">      <span class="comment">//获取旋转中心坐标</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> PointF <span class="title">getCenter</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> PointF(</span><br><span class="line">                (mCurrent.x + mOrigin.x) / <span class="number">2</span>,</span><br><span class="line">                (mCurrent.y + mOrigin.y) / <span class="number">2</span></span><br><span class="line">        );</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>旋转触摸事件处理<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onTouchEvent</span><span class="params">(MotionEvent event)</span> </span>&#123;</span><br><span class="line">        PointF current = <span class="keyword">new</span> PointF( event.getX(),event.getY());</span><br><span class="line">        String action = <span class="string">""</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">switch</span> (event.getActionMasked())&#123;</span><br><span class="line"></span><br><span class="line">            ...</span><br><span class="line"></span><br><span class="line">            <span class="keyword">case</span> MotionEvent.ACTION_MOVE:</span><br><span class="line">                action = <span class="string">"ACTION_MOVE"</span>;</span><br><span class="line">                <span class="keyword">if</span> (mCurrentBox != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (event.getPointerCount() == <span class="number">1</span> &amp;&amp; mCurrentBox.getCurrentAngle() == <span class="number">0</span>) &#123;</span><br><span class="line">                        <span class="comment">//如果只有一只手指按下，而且还未曾旋转过的话，就进行大小的缩放</span></span><br><span class="line">                        mCurrentBox.setCurrent(current);</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="comment">// 如果按下了两根手指</span></span><br><span class="line">                    <span class="keyword">if</span> (event.getPointerCount() == <span class="number">2</span>) &#123;</span><br><span class="line">                        <span class="comment">//获取角度</span></span><br><span class="line">                        <span class="keyword">float</span> angle = (<span class="keyword">float</span>) (Math.atan((event.getY(<span class="number">1</span>) - event.getY(<span class="number">0</span>)) /</span><br><span class="line">                                (event.getX(<span class="number">1</span>) - event.getX(<span class="number">0</span>))) * <span class="number">180</span> / Math.PI);</span><br><span class="line">                        Log.i(TAG, <span class="string">"onTouchEvent: angle:"</span> + (angle - mCurrentBox.getOriginAngle()));</span><br><span class="line">                        <span class="comment">// 已旋转的角度 = 之前旋转的角度 + 新旋转的角度</span></span><br><span class="line">                        <span class="comment">// 新旋转的角度 = 本次 move 到的角度 - 手指按下的角度</span></span><br><span class="line">                        mCurrentBox.setCurrentAngle(mCurrentBox.getCurrentAngle() + angle</span><br><span class="line">                                - mCurrentBox.getOriginAngle());</span><br><span class="line">                        mCurrentBox.setOriginAngle(angle);</span><br><span class="line">                    &#125;</span><br><span class="line">                    invalidate();</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> MotionEvent.ACTION_POINTER_DOWN:</span><br><span class="line">                action = <span class="string">"POINTER_DOWN"</span>;</span><br><span class="line">                <span class="comment">//两根手指同时按下</span></span><br><span class="line">                <span class="keyword">if</span> (event.getPointerCount() == <span class="number">2</span>) &#123;</span><br><span class="line">                    <span class="comment">// 首先获取按下时的角度（有一个弧度转角度的过程）</span></span><br><span class="line">                    <span class="comment">// 每次按下的时候将角度存入现在矩形的原始角度</span></span><br><span class="line">                    <span class="keyword">float</span> angle = (<span class="keyword">float</span>) (Math.atan((event.getY(<span class="number">1</span>) - event.getY(<span class="number">0</span>)) /</span><br><span class="line">                            (event.getX(<span class="number">1</span>) - event.getX(<span class="number">0</span>))) * <span class="number">180</span> / Math.PI);</span><br><span class="line">                    mCurrentBox.setOriginAngle(angle);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">          ...</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">        Log.e( TAG,action + <span class="string">" at x = "</span> + current.x +</span><br><span class="line">                <span class="string">",y = "</span> + current.y);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<hr>
<p>GIthub 具体代码：<a href="https://github.com/wanghao15536870732/Android-programming-authority-guide/tree/master/DragAndDraw" target="_blank" rel="noopener">hyyyrwang.github.io</a></p>

      
    </div>
    
    
    

    

    

    

    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"><i class="fa fa-tag"></i> Android</a>
          
            <a href="/tags/Android编程权威指南-第2版/" rel="tag"><i class="fa fa-tag"></i> Android编程权威指南(第2版)</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/31/android/Android编程权威指南/android-note-11/" rel="next" title="Android编程权威指南（第2版）学习笔记 --第28章 网页浏览">
                <i class="fa fa-chevron-left"></i> Android编程权威指南（第2版）学习笔记 --第28章 网页浏览
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/31/android/Android编程权威指南/android-note-13/" rel="prev" title="Android编程权威指南（第2版）学习笔记 --第30章 属性动画篇 挑战练习">
                Android编程权威指南（第2版）学习笔记 --第30章 属性动画篇 挑战练习 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zOTQxMi8xNTkzOQ=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/uploads/icon.jpg"
                alt="HyYyr Wang" />
            
              <p class="site-author-name" itemprop="name">HyYyr Wang</p>
              <p class="site-description motion-element" itemprop="description">我不是程序员，也不是设计师，只是喜欢编程，热爱python，碰巧有一些想法跟一台电脑</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">24</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/wanghao15536870732" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:hyyyrwang@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.douban.com/people/183791128" target="_blank" title="豆瓣">
                      
                        <i class="fa fa-fw fa-globe"></i>豆瓣</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/be-forever-82/activities" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-globe"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/964bc0f1e88e" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-globe"></i>简书</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_41005535" target="_blank" title="CSND">
                      
                        <i class="fa fa-fw fa-globe"></i>CSND</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                推荐阅读
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="npm install hexo-wordcount --save" title="秋冬夜漫长" target="_blank">秋冬夜漫长</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://angus-liu.github.io" title="Angus-Liu" target="_blank">Angus-Liu</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://innofang.github.io" title="Inno Fang" target="_blank">Inno Fang</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://barackbao.com" title="Barack Bao" target="_blank">Barack Bao</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://wmpscc.github.io" title="wmpscc" target="_blank">wmpscc</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://kentanvictor.github.io" title="JohnnyTan" target="_blank">JohnnyTan</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://xmmmmmovo.github.io/" title="xmmmmmovo Zha" target="_blank">xmmmmmovo Zha</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#创建定制视图"><span class="nav-number">1.</span> <span class="nav-text">创建定制视图</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Android-视图分类"><span class="nav-number">1.1.</span> <span class="nav-text">Android 视图分类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建定制视图三步骤"><span class="nav-number">1.2.</span> <span class="nav-text">创建定制视图三步骤</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建BoxDrawingView"><span class="nav-number">1.3.</span> <span class="nav-text">创建BoxDrawingView</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#BoxDrawingView-是一个简单的视图，同时也是View的直接子类"><span class="nav-number">1.3.1.</span> <span class="nav-text">BoxDrawingView 是一个简单的视图，同时也是View的直接子类</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#在布局当中添加该View"><span class="nav-number">1.3.2.</span> <span class="nav-text">在布局当中添加该View</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#处理触摸事件"><span class="nav-number">2.</span> <span class="nav-text">处理触摸事件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#触摸事件简介"><span class="nav-number">2.1.</span> <span class="nav-text">触摸事件简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实现BoxDrawingView视图类"><span class="nav-number">2.2.</span> <span class="nav-text">实现BoxDrawingView视图类</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#跟踪运动事件"><span class="nav-number">3.</span> <span class="nav-text">跟踪运动事件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#首先，要知道定义矩形的两个坐标点，需要定义一个类用于储存这两个坐标值"><span class="nav-number">3.1.</span> <span class="nav-text">首先，要知道定义矩形的两个坐标点，需要定义一个类用于储存这两个坐标值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#添加拖拽生命周期方法-BoxDrawingView-java"><span class="nav-number">3.2.</span> <span class="nav-text">添加拖拽生命周期方法  BoxDrawingView.java</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#onDraw-…-方法内的绘制图形"><span class="nav-number">4.</span> <span class="nav-text">onDraw(…)方法内的绘制图形</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#onDeaw绘制简介"><span class="nav-number">4.1.</span> <span class="nav-text">onDeaw绘制简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建Point"><span class="nav-number">4.2.</span> <span class="nav-text">创建Point</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-覆盖onDraw-方法"><span class="nav-number">4.3.</span> <span class="nav-text">4.3 覆盖onDraw()方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-挑战练习"><span class="nav-number">5.</span> <span class="nav-text">5. 挑战练习</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1-设备旋转问题"><span class="nav-number">5.1.</span> <span class="nav-text">5.1 设备旋转问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-旋转矩形框"><span class="nav-number">5.2.</span> <span class="nav-text">5.2 旋转矩形框</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HyYyr Wang</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>


<div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span> </span>
<span id="busuanzi_container_site_uv" style='display:none'>
    有 <span id="busuanzi_value_site_uv"></span> 人看过我的博客啦
</span>
</div>





<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共33.8k字</span>
</div>

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
